package com.shareppy.nomrnaui.list.adapters;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.shareppy.norman_ui.R;

public class JsonAdapter extends ArrayAdapter<JSONObject> {

	private JSONArray array;
	private int resourceId;
	private SparseArray<String> mapping;

	public JsonAdapter(Context ctx, int resourceId, JSONArray array,
			SparseArray<String> mapping) {
		super(ctx, resourceId);
		this.array = array;
		this.resourceId = resourceId;
		this.mapping = mapping;
	}

	@Override
	public int getCount() {
		return array.length();
	}

	@Override
	public JSONObject getItem(int index) {
		try {
			return (JSONObject) array.get(index);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int index, View view, ViewGroup parent) {
		View v = View.inflate(getContext(), resourceId, null);
		v.setBackgroundResource(index % 2 == 0 ? R.color.list_row_odd_color
				: R.color.list_row_even_color);
		JSONObject item = getItem(index);
		for (int i = 0; i < mapping.size(); i++) {
			int viewId = mapping.keyAt(i);
			String property = mapping.get(viewId);
			if (item.has(property)) {
				View viewItem = v.findViewById(viewId);
				if (viewItem instanceof TextView) {
					TextView tv = (TextView) viewItem;
					try {
						tv.setText(item.getString(property));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return v;
	}
}